// Copyright 2008 web2me.dev
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package net.web2me.parsers;

import net.web2me.api.AbstractBaseParser;
import net.web2me.api.ParserException;
import net.web2me.api.util.DocumentGenerator;
import net.web2me.api.util.Downloader;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class ClubLezParser extends AbstractBaseParser {
	
	public void process(String siteStream) throws ParserException {
		
		Downloader downloader = new Downloader();
		Document document = null;
		
		try {
			document = DocumentGenerator.generate( siteStream );
		} catch (Exception e) {
			throw new ParserException(e);
		}
		
		NodeList links = document.getElementsByTagName("a");
		
		for (int i = 0; i < links.getLength(); i++) {
			Element link = (Element)links.item(i);
			String href = link.getAttribute("href");
			String finalUrl = "";
			
			if( href.indexOf("javascript:void(0)") > -1){
				//The oldest type of gallery
				String onClick = link.getAttribute("onclick");
				
				int start = onClick.indexOf("'");
				int end = onClick.indexOf("'", start + 1);
				
				if( start > -1 && end > -1){
					String subOnClick = onClick.substring(start + 1, end);
					finalUrl = getUrl().replaceAll("/index.html", "") + "/" + subOnClick;
				}
			}
			
			if( href.indexOf("javascript") > -1 ){
				//Old type galleries
				int start = href.indexOf("'");
				int end = href.indexOf("'", start + 1);
				
				if( start > -1 && end > -1){
					String subHref = href.substring(start + 1, end);
					finalUrl = getUrl().replaceAll("/index.html", "") + "/" + subHref;
				}
			}else{
				//New type galleries
				if(href.toLowerCase().endsWith(".jpg")){
					finalUrl = getUrl().replaceAll("/index.html", "") + "/" + href;
				}else{
					//Not a valid image link
					continue;
				}
			}
			
			if( !"".equals(finalUrl) ){
				try {
					downloader.setDestinyDirectory(getDir());
					downloader.setUrl(finalUrl);
					
					Thread t = new Thread(downloader);
					t.start();
				} catch (RuntimeException e) {
					throw new ParserException(e);
				}	
			}
		}
	}

}
